package net.daum.webtoon.android;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import net.daum.webtoon.android.jibx.data.Item;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class ViewListActivity extends Activity {

	public static String TAG = ViewListActivity.class.getSimpleName();
	private ListView mView;
	private final String TOONRSS = "http://cartoon.media.daum.net/webtoon/rss/";
	private final String TOONDOMAIN = "http://cartoon.media.daum.net/";
	private final String TOONVIEWDATA = "/webtoon/viewer_images.js?webtoon_episode_id=";
	public static final String TOONNAME = "TOONNAME";

//	public static final String TOONNAME = "TOONNAME";
//	public static final String TOONNAME = "TOONNAME";
	private ArrayList<Item> mItem;
	Handler gBaseHandler = new Handler();
	String mToonName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);

		mToonName = getIntent().getStringExtra(TOONNAME);
		new Thread(new Runnable() {

			@Override
			public void run() {
				connect("http://cartoon.media.daum.net/webtoon/viewer_images.js?webtoon_episode_id=18760");
			}
		}, TAG).start();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private class WebToonListAdapter extends ArrayAdapter<Item> {

		public WebToonListAdapter(Context context, ArrayList<Item> aLis) {
			super(context, R.layout.content_item, aLis);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			ViewWrapper wrapper = null;

			if (row == null) {
				row = getLayoutInflater().inflate(R.layout.content_item, null);
				wrapper = new ViewWrapper(row);
				row.setTag(wrapper);
			} else
				wrapper = (ViewWrapper) row.getTag();

			Item info = mItem.get(position);
			wrapper.getBase().setBackgroundColor((position % 2) == 0 ? android.R.color.background_dark : android.R.color.background_light);
//			downLoadThumb(info.getDescription().split("'")[1], wrapper.getThumbImgage());
			wrapper.getImgage().setImageBitmap(getBitmapDrawable(info.getDescription().split("'")[1]));
//			wrapper.getNumofContent().setText(info.getDescription());

			return row;
		}

		private class ViewWrapper {
			private View mmmBase;
//			private TextView numOfContent;
			private ImageView mmmView;

			public ViewWrapper(View base) {
				mmmBase = base;
			}

			public View getBase() {
				return mmmBase;
			}

			public ImageView getImgage() {
				if (mmmView == null) {
					mmmView = (ImageView) mmmBase.findViewById(R.id.content);
//					mmmthumb.setSelected(true);
				}
				return mmmView;
			}

		}

	}

	public void downLoadThumb(final String url) {
		try {

			String lFileName = makeFileName(url);

			URL lurl = new URL(url);
			URLConnection conn = lurl.openConnection();
			conn.connect();
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			final Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();

			saveFile(bm, lFileName);

		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}
	}

	public Bitmap getBitmapDrawable(String aUrl) {
		File lTempFile = null;
		String fileName = makeFileName(aUrl);
		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getApplicationContext().getPackageName()
				+ "/temp";

		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lPath = new File(path);
			if (!lPath.exists())
				lPath.mkdirs();

			lTempFile = new File(path, fileName);
			if (lTempFile.exists())
				return BitmapFactory.decodeFile(lTempFile.getAbsolutePath());
		}

		return BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
	}

	private String makeFileName(String aUrl) {
		String[] returnStrs = aUrl.split("/");
		return returnStrs[returnStrs.length - 1];
	}

	private void saveFile(Bitmap bitmap, String fileName) {
		File lTempFile = null;

		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + getApplicationContext().getPackageName()
				+ "/temp";

		String extState = Environment.getExternalStorageState();

		if (extState.equals(Environment.MEDIA_MOUNTED)) {
			File lPath = new File(path);
			if (!lPath.exists())
				lPath.mkdirs();

			lTempFile = new File(path, fileName);

			FileOutputStream out;

			try {
				out = new FileOutputStream(lTempFile);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

	}

	private String connect(String url) {

		// Create the httpclient
		HttpClient httpclient = new DefaultHttpClient();

		// Prepare a request object
		HttpGet httpget = new HttpGet(url);

		// Execute the request
		HttpResponse response;

		// return string
		String returnString = null;

		try {

			// Open the webpage.
			response = httpclient.execute(httpget);

			if (true) {
				// Connection was established. Get the content.

				HttpEntity entity = response.getEntity();
				// If the response does not enclose an entity, there is no need
				// to worry about connection release

				if (entity != null) {
					// A Simple JSON Response Read
					InputStream instream = entity.getContent();

					// Load the requested page converted to a string into a JSONObject.
					JSONObject myAwway = new JSONObject(convertStreamToString(instream));

					// Get the query value'
					String query = myAwway.getString("query");

					// Make array of the suggestions
					JSONArray suggestions = myAwway.getJSONArray("suggestions");

					// Build the return string.
					returnString = "Found: " + suggestions.length() + " locations for " + query;
					for (int i = 0; i < suggestions.length(); i++) {
						returnString += "\n\t" + suggestions.getString(i);
					}

					// Cose the stream.
					instream.close();
				}
			} else {
				// code here for a response othet than 200.  A response 200 means the webpage was ok
				// Other codes include 404 - not found, 301 - redirect etc...
				// Display the response line.
				returnString = "Unable to load page - " + response.getStatusLine();
			}
		} catch (IOException ex) {
			// thrown by line 80 - getContent();
			// Connection was not established
			returnString = "Connection failed; " + ex.getMessage();
		} catch (JSONException ex) {
			// JSON errors
			returnString = "JSON failed; " + ex.getMessage();
		}
		Log.d(TAG, returnString);
		return returnString;
	}

	private static String convertStreamToString(InputStream is) {
		/* To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String. */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

}
